
import { Component, Watch } from 'vue-property-decorator';
import { VueLifeCycleProcessing,AppControlBase } from 'ibiz-vue';
import { AppGridBase } from 'ibiz-vue';
import { DataServiceHelp, AppServiceBase, GetModelService, LogUtil, Util, ViewTool, UIServiceHelp, ModelTool } from 'ibiz-core';
import { IPSAppDataEntity, IPSAppDERedirectView, IPSAppDEView, IPSAppUILogicRefView, IPSAppUIOpenDataLogic, IPSAppView, IPSAppViewLogic, IPSAppViewRef, IPSNavigateContext, IPSNavigateParam } from '@ibiz/dynamic-model-api';
import { Subject } from 'rxjs';


/**
 * 工作流表格插件插件类
 *
 * @export
 * @class WFGRID
 * @class WFGRID
 * @extends {Vue}
 */
@Component({})
@VueLifeCycleProcessing()
export class WFGRID extends AppGridBase {

    /**
     * 行单击选中
     *
     * @param {*} row 行
     * @param {*} column 列
     * @param {*} event 点击事件
     * @param {boolean} ifAlways
     * @returns {void}
     * @memberof WFGRID
     */
    public rowClick(row: any, column?: any, event?: any, ifAlways: boolean = false): void {
        // 分组行跳过
        if (row && row.children) {
            return;
         }
         if (!ifAlways && (!row || this.actualIsOpenEdit)) {
             return;
         }
         if (this.stopRowClick) {
             this.stopRowClick = false;
             return;
         }
         if (this.appDeCodeName && Object.is(this.appDeCodeName, 'WFTask')) {
             this.excuteWFTaskOpenView(Util.deepCopy(row));
         } else {
             //是否是分组列，是分组列时选中数据
             const isSelectColumn: boolean = column && Object.is(column.type, 'selection') ? true : false;
             if (this.isSingleSelect) {
                 this.selections = [];
             }
             if (this.gridRowActiveMode == 1 && !isSelectColumn) {
                 this.ctrlEvent({ controlname: this.name, action: "selectiondata", data: [Util.deepCopy(row)] });
                 this.excuteOpenView(Util.deepCopy(row));
             } else if (this.gridRowActiveMode == 2 || isSelectColumn) {
                 // 已选中则删除，没选中则添加
                 const appDeCodeName = this.controlInstance.getPSAppDataEntity()?.codeName || '';
                 let selectIndex = -1;
                 if (appDeCodeName) {
                     selectIndex = this.selections.findIndex((item: any) => {
                         return Object.is(item[appDeCodeName.toLowerCase()], row[appDeCodeName.toLowerCase()]);
                     });
                 }
                 if (Object.is(selectIndex, -1)) {
                     this.selections.push(Util.deepCopy(row));
                 } else {
                     this.selections.splice(selectIndex, 1);
                 }
                 const table: any = (this.$refs as any)[this.gridRefName];
                 if (table) {
                     if (this.isSingleSelect) {
                         table.clearSelection();
                         table.setCurrentRow(row);
                     } else {
                         table.toggleRowSelection(row);
                     }
                 }
                 this.ctrlEvent({ controlname: this.name, action: "selectiondata", data: this.selections });
             }
         }
    }

    /**
     * 行双击事件
     *
     * @param {*} $event
     * @returns {void}
     * @memberof WFGRID
     */
    public rowDBLClick($event: any): void {
        // 分组行跳过
        if ($event && $event.children) {
            return;
        }
        if (!$event || this.actualIsOpenEdit || Object.is(this.gridRowActiveMode, 0)) {
            return;
        }
        if (this.appDeCodeName && Object.is(this.appDeCodeName, 'WFTask')) {
            this.excuteWFTaskOpenView(Util.deepCopy($event));
        } else {
            this.excuteOpenView(Util.deepCopy($event));
       }
    }

    /**
     * 执行打开视图
     *
     * @param {*} $event
     * @returns {void}
     * @memberof WFGRID
     */
    public excuteOpenView(data: any) {
        if (!this.viewparams || !this.viewparams.n_todosubtype_eq) {
            return;
        }
        if (Object.is(this.viewparams.n_todosubtype_eq, 'Undo')) {
            let localParams: any = [{ [data.biztype]: data.bizkey }];
            this.openTargetData(this.controlInstance.getParentPSModelObject(), localParams, [data], null, this);
        } else {
            this.openRedirectView(data);
        }
    }

    /**
     * 重定向跳转
     *
     * @param {*} $event
     * @returns {void}
     * @memberof WFGRID
     */
    public openRedirectView(data: any) {
        if(!this.viewparams.hasOwnProperty('n_todosubtype_eq')){
            LogUtil.warn('未配置导航数据，请确认');
            return;
        }
        const appDeCodename: string = (this.controlInstance?.getPSAppDataEntity?.()?.codeName as string).toLowerCase();
        if (data && data[appDeCodename]) {
            this.$http.post(`/systodos/${data[appDeCodename]}/getlinkurl`, {todourltype:'RouterUrl',todosubtype:this.viewparams.n_todosubtype_eq,srfapptype: 'pc',srfapp: AppServiceBase.getInstance().getAppModelDataObject().codeName}).then((response: any) => {
                if (response && response.status == 200 && response.data && response.data.linkurl) {
                    let targetUrl:string = response.data.linkurl;
                    if (targetUrl.indexOf('/') != 0) {
                        targetUrl = '/' + targetUrl;
                    }
				  			 targetUrl = `${targetUrl.slice(0, targetUrl.indexOf(';srffullscreen=true'))}`;
                    targetUrl += `;srfwf=${this.viewparams.n_todosubtype_eq}`;
                    this.$router.push("/appindexview"+targetUrl);
                } else {
                    if (response) {
                        this.$throw(response);
                    }
                }
            }).catch((response: any) => {
                this.$throw(response);
            });
        }
    }

    /**
     * 执行打开视图(WFTask)
     *
     * @param {*} data
     * @returns {void}
     * @memberof WFGRID
     */
    public excuteWFTaskOpenView(data: any) {
        if (data && this.viewparams && this.viewparams.processtype) {
            this.openWFTaskRedirectView(data);
        }
    }

    /**
     * 重定向跳转(WFTask)
     *
     * @param {*} data
     * @returns {void}
     * @memberof WFGRID
     */
    public openWFTaskRedirectView(data: any) {
        try {
            Object.assign(this.context, { wftask: data.wftask });
            DataServiceHelp.getInstance().getService(this.controlInstance.getPSAppDataEntity()).then((service: any) => {
                service.execute('GetWFTaskUrl',this.context, { id: data.wftask, name: this.viewparams.processtype }).then((res: any) => {
                    let targetUrl: string = res.data.url;
                    targetUrl = targetUrl.slice(0, targetUrl.indexOf(';srffullscreen=true'));
                    if (targetUrl && targetUrl.indexOf('appredirectview')) {
                        targetUrl = targetUrl.slice(targetUrl.indexOf('appredirectview'));
                        if (targetUrl.indexOf('/') != 0) {
                            targetUrl = '/' + targetUrl;
                        }
                        this.$router.push(targetUrl);
                    }
                })
            })
        } catch (error) {
            console.log(error);
        }
    }

    /**
     * 打开目标数据
     *
     * @memberof WFGRID
     */
    public async openTargetData(viewInstance: any, args: any[], fullargs?: any, $event?: any, xData?: any) {
        const openAppViewLogic: IPSAppViewLogic | null = viewInstance.findPSAppViewLogic('opendata');
        if (!openAppViewLogic || !openAppViewLogic.getPSAppUILogic()) {
            return;
        }
        let viewOpenAppUIlogic:
            | IPSAppUIOpenDataLogic
            | undefined
            | null = openAppViewLogic.getPSAppUILogic() as IPSAppUIOpenDataLogic;
        if (viewOpenAppUIlogic?.getOpenDataPSAppView()) {
            const openViewRef: IPSAppUILogicRefView = viewOpenAppUIlogic.getOpenDataPSAppView() as IPSAppUILogicRefView;
            const data: any = {};
            let tempContext = JSON.parse(JSON.stringify(this.context));
            // 准备参数
            if (args.length > 0) {
                Object.assign(tempContext, args[0]);
            }
            if (
                openViewRef?.getPSNavigateContexts() &&
                (openViewRef?.getPSNavigateContexts() as IPSNavigateContext[])?.length > 0
            ) {
                const localContext = Util.formatNavParam(openViewRef.getPSNavigateContexts());
                let _context: any = Util.computedNavData(fullargs[0], this.context, this.viewparams, localContext);
                Object.assign(tempContext, _context);
            }
            if (
                openViewRef?.getPSNavigateParams() &&
                (openViewRef.getPSNavigateParams() as IPSNavigateParam[])?.length > 0
            ) {
                const localViewParam = Util.formatNavParam(openViewRef.getPSNavigateParams());
                let _param: any = Util.computedNavData(fullargs[0], this.context, this.viewparams, localViewParam);
                Object.assign(data, _param);
            }
            if (
                fullargs &&
                fullargs.length > 0 &&
                fullargs[0]['srfprocessdefinitionkey'] &&
                fullargs[0]['srftaskdefinitionkey']
            ) {
                Object.assign(data, { processDefinitionKey: fullargs[0]['srfprocessdefinitionkey'] });
                Object.assign(data, { taskDefinitionKey: fullargs[0]['srftaskdefinitionkey'] });
                // 将待办任务标记为已读准备参数
                const that: any = this;
                if (that.quickGroupData && that.quickGroupData.hasOwnProperty('srfwf') && fullargs[0]['srftaskid']) {
                    Object.assign(data, { srfwf: that.quickGroupData['srfwf'] });
                    Object.assign(data, { srftaskid: fullargs[0]['srftaskid'] });
                }
            }
            let deResParameters: any[] = [];
            let parameters: any[] = [];
            const openView: IPSAppView | null = openViewRef.getRefPSAppView();
            if (!openView) return;
            await openView.fill(true);
            if (openView.getPSAppDataEntity()) {
                // 处理视图关系参数 （只是路由打开模式才计算）
                if (!openView.openMode || openView.openMode == 'INDEXVIEWTAB' || openView.openMode == 'POPUPAPP') {
                    deResParameters = Util.formatAppDERSPath(
                        tempContext,
                        (openView as IPSAppDEView).getPSAppDERSPaths(),
                    );
                }
            }
            if (!openView?.openMode || openView.openMode == 'INDEXVIEWTAB') {
                if (openView.getPSAppDataEntity()) {
                    parameters = [
                        {
                            pathName: Util.srfpluralize(
                                (openView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName,
                            ).toLowerCase(),
                            parameterName: (openView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName.toLowerCase(),
                        },
                        {
                            pathName: 'views',
                            parameterName: ((openView as IPSAppDEView).getPSDEViewCodeName() as string).toLowerCase(),
                        },
                    ];
                } else {
                    parameters = [{ pathName: 'views', parameterName: openView.name?.toLowerCase() }];
                }
            } else {
                if (openView?.getPSAppDataEntity()) {
                    parameters = [
                        {
                            pathName: Util.srfpluralize(
                                (openView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName,
                            )?.toLowerCase(),
                            parameterName: (openView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName?.toLowerCase(),
                        },
                    ];
                }
                if (openView && openView.modelPath) {
                    Object.assign(tempContext, { viewpath: openView.modelPath });
                }
            }
            // 关闭视图回调
            let callback: Function = (result: any, xData: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                if (!xData || !(xData.refresh instanceof Function)) {
                    return;
                }
                xData.refresh(result.datas);
            };
            // 重定向视图
            if (openView?.redirectView) {
                let targetRedirectView: IPSAppDERedirectView = openView as IPSAppDERedirectView;
                await targetRedirectView.fill();
                if (
                    targetRedirectView.getRedirectPSAppViewRefs() &&
                    targetRedirectView.getRedirectPSAppViewRefs()?.length === 0
                ) {
                    return;
                }
                let result: string = "EDITVIEW:" + fullargs[0].biztype.toUpperCase();
			        const type: string = fullargs[0].biztype?.toLowerCase();
                const App = AppServiceBase.getInstance().getAppModelDataObject();
                const targetEntity = App.getAllPSAppDataEntities()?.find((appDataEntity: IPSAppDataEntity) => {
                    return appDataEntity.codeName === ModelTool.getAppEntityCodeNameByName(type);
                })
                if(!targetEntity) return;
                const redirectUIService: any = await UIServiceHelp.getInstance().getService(targetEntity,{context:this.context});
                const response: any = await redirectUIService.getRDAppView(
                    tempContext,
                    args[0][fullargs[0].biztype],
                    data,
                );
                if(response.param.split(':')[1]){
                    this.modelService = await GetModelService(tempContext);
                    const dynainstParam:any = this.modelService.app.M.getPSDynaInsts.find((item:any) =>{
                        return item.instTag2 == response.param.split(':')[1];
                    })
                    Object.assign(tempContext, { srfdynainstid: dynainstParam.id });
                }
                let targetOpenViewRef:
                    | IPSAppViewRef
                    | undefined = targetRedirectView.getRedirectPSAppViewRefs()?.find((item: IPSAppViewRef) => {
                        return item.name === result;
                    });
                if (!targetOpenViewRef) {
                    console.log("未找到目标视图,请确认重定向视图配置");
                    return;
                }
                if (
                    targetOpenViewRef.getPSNavigateContexts() &&
                    (targetOpenViewRef.getPSNavigateContexts() as IPSNavigateContext[]).length > 0
                ) {
                    let localContextRef: any = Util.formatNavParam(
                        targetOpenViewRef.getPSNavigateContexts(),
                        true,
                    );
                    let _context: any = Util.computedNavData(fullargs[0], tempContext, data, localContextRef);
                    Object.assign(tempContext, _context);
                }
                let targetOpenView: IPSAppView | null = targetOpenViewRef.getRefPSAppView();
                if (!targetOpenView) {
                    return;
                }
                await targetOpenView.fill(true);
                const view: any = {
                    viewname: Util.srfFilePath2(targetOpenView.codeName),
                    height: targetOpenView.height,
                    width: targetOpenView.width,
                    title: this.$tl(targetOpenView.getCapPSLanguageRes()?.lanResTag, targetOpenView.caption),
                };
                if (!targetOpenView.openMode || targetOpenView.openMode == 'INDEXVIEWTAB') {
                    if (targetOpenView.getPSAppDataEntity()) {
                        deResParameters = Util.formatAppDERSPath(
                            tempContext,
                            (targetOpenView as IPSAppDEView).getPSAppDERSPaths(),
                        );
                        parameters = [
                            {
                                pathName: Util.srfpluralize(
                                    (targetOpenView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName,
                                ).toLowerCase(),
                                parameterName: (targetOpenView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName.toLowerCase(),
                            },
                            {
                                pathName: 'views',
                                parameterName: ((targetOpenView as IPSAppDEView).getPSDEViewCodeName() as string).toLowerCase(),
                            },
                        ];
                    } else {
                        parameters = [
                            {
                                pathName: targetOpenView.codeName.toLowerCase(),
                                parameterName: targetOpenView.codeName.toLowerCase(),
                            },
                        ];
                    }
                } else {
                    if (targetOpenView.getPSAppDataEntity()) {
                        parameters = [
                            {
                                pathName: Util.srfpluralize(
                                    (targetOpenView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName,
                                ).toLowerCase(),
                                parameterName: (targetOpenView.getPSAppDataEntity() as IPSAppDataEntity)?.codeName.toLowerCase(),
                            },
                        ];
                    }
                    if (targetOpenView && targetOpenView.modelPath) {
                        Object.assign(tempContext, { viewpath: targetOpenView.modelPath });
                    }
                }
                this.openTargtView(
                    targetOpenView,
                    view,
                    tempContext,
                    data,
                    xData,
                    $event,
                    deResParameters,
                    parameters,
                    args,
                    callback,
                );
            } else {
                if (fullargs && fullargs.copymode) {
                    Object.assign(data, { copymode: true });
                }
                let view: any = {
                    viewname: 'app-view-shell',
                    height: openView.height,
                    width: openView.width,
                    title: this.$tl(openView.getCapPSLanguageRes()?.lanResTag, openView.caption),
                };
                this.openTargtView(
                    openView,
                    view,
                    tempContext,
                    data,
                    xData,
                    $event,
                    deResParameters,
                    parameters,
                    args,
                    callback,
                );
            }
        } else {
            this.$warning(this.$t('app.nosupport.unassign'), 'opendata');
        }
    }

    /**
     * 打开目标视图
     *
     * @memberof WFGRID
     */
    public openTargtView(
        openView: any,
        view: any,
        tempContext: any,
        data: any,
        xData: any,
        $event: any,
        deResParameters: any,
        parameters: any,
        args: any,
        callback: Function,
    ) {
        const _this: any = this;
        if (!openView?.openMode || openView.openMode == 'INDEXVIEWTAB') {
            if (tempContext.srfdynainstid) {
                Object.assign(data, { srfdynainstid: tempContext.srfdynainstid });
            }
            const routePath = ViewTool.buildUpRoutePath(
                _this.$route,
                tempContext,
                deResParameters,
                parameters,
                args,
                data,
            );
            _this.$router.push(routePath);
        } else if (openView.openMode == 'POPUPAPP') {
            const routePath = ViewTool.buildUpRoutePath(
                _this.$route,
                tempContext,
                deResParameters,
                parameters,
                args,
                data,
            );
            window.open('./#' + routePath, '_blank');
        } else if (openView.openMode == 'POPUPMODAL') {
            // 打开模态
            let container: Subject<any> = _this.$appmodal.openModal(view, tempContext, data);
            container.subscribe((result: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                callback(result, xData);
            });
        } else if (openView.openMode.indexOf('DRAWER') !== -1) {
            // 打开抽屉
            if (Object.is(openView.openMode, 'DRAWER_TOP')) {
                Object.assign(view, { isfullscreen: true });
                let container: Subject<any> = _this.$appdrawer.openTopDrawer(
                    view,
                    Util.getViewProps(tempContext, data),
                );
                container.subscribe((result: any) => {
                    callback(result, xData);
                });
            } else {
                Object.assign(view, { placement: openView.openMode });
                let container: Subject<any> = _this.$appdrawer.openDrawer(view, Util.getViewProps(tempContext, data));
                container.subscribe((result: any) => {
                    callback(result, xData);
                });
            }
        } else if (openView.openMode == 'POPOVER') {
            // 打开气泡卡片
            Object.assign(view, { placement: openView.openMode });
            let container: Subject<any> = _this.$apppopover.openPop($event, view, tempContext, data);
            container.subscribe((result: any) => {
                callback(result, xData);
            });
        } else {
            this.$warning(openView.title + this.$t('app.nosupport.unopen'), 'openTargtView');
        }
    }

}


